#!/bin/bash

. /etc/profile

echo "kawins 2018-9-18"

set -e

DEF_CCSN="xas"
DEF_ENV="@temp"
APP_NAME="@temp"
APP_NAME_ENV="@temp"
APP_NET="@temp"
IMAGE_VER="@temp"
IMAGE_NAME="@temp"
DOCKER_ADDR="@temp"
JAVA_OPTS="@temp"
JAVA_PARAMS="@temp"
DOCKER_RUNS="@temp"

#-----------------------------------------------------------------------------------

if [[ `docker ps --filter name=${APP_NAME_ENV} | grep ${APP_NAME_ENV}` ]];
then
  echo ">>>>>>>>>>docker stop<<<<<<<<<<"
  docker stop ${APP_NAME_ENV}
fi;

if [[ `docker ps -a --filter name=${APP_NAME_ENV} | grep ${APP_NAME_ENV}` ]];
then
  echo ">>>>>>>>>>docker rm<<<<<<<<<<"
	docker rm ${APP_NAME_ENV}
fi;


if [[ `docker images ${DOCKER_ADDR}/${IMAGE_NAME} | grep ${DOCKER_ADDR}/${IMAGE_NAME}` ]];
then
  echo ">>>>>>>>>>docker rmi<<<<<<<<<<"
	docker rmi ${DOCKER_ADDR}/${IMAGE_NAME}:${IMAGE_VER}
fi;

echo ">>>>>>>>>>docker build<<<<<<<<<<"
docker build -t ${IMAGE_NAME}:${IMAGE_VER} $(cd `dirname $0`; pwd)
docker tag ${IMAGE_NAME}:${IMAGE_VER} ${DOCKER_ADDR}/${IMAGE_NAME}:${IMAGE_VER}
docker rmi ${IMAGE_NAME}:${IMAGE_VER}

echo ">>>>>>>>>>docker run<<<<<<<<<<"
docker run -d \
    --init \
    --cap-add=ALL \
    --name ${APP_NAME_ENV} \
    --restart=always \
    --privileged=true \
    --oom-kill-disable=false \
    ${APP_NET} \
    -e ENV=${ENV:-${DEF_ENV}} \
    -e CCSN=${CCSN:-${DEF_CCSN}} \
    -e JAVA_OPTS="${JAVA_OPTS}" \
    -e PARAMS="-Dcom.sun.management.jmxremote.port=7091
               -Dcom.sun.management.jmxremote.ssl=false
               -Dcom.sun.management.jmxremote.rmi.port=7091
               -Dcom.sun.management.jmxremote.authenticate=false
               ${JAVA_PARAMS}" \
    ${DOCKER_RUNS} \
    -v $(cd `dirname $0`; pwd)/logs/:/logs \
    -v /etc/localtime:/etc/localtime:ro \
    -v /etc/resolv.conf:/etc/resolv.conf:ro \
    ${DOCKER_ADDR}/${IMAGE_NAME}:${IMAGE_VER}

#网络模式1:
# docker network create basic
# --network basic
# --network-alias basic
#网络模式2:
#docker network create -d macvlan --subnet=192.168.2.1/24 --gateway=192.168.1.1 -o parent=eth0 macvlan0
#--network macvlan0 --ip 192.168.2.2

#在run的时候每个服务都有一个环境变量参数"JAVA_OPTS"和"PARAM"
#JAVA_OPTS主要用来设置JVM启动参数
#PARAM主要用来修改项目的配置参数如:
#-e PARAM="-Dserver.port=8080 \
#          -Dspring.profiles.active=xas,nas \
#          -Dspring.application.name=gradle-service"
#打开远程调试
#-e JAVA_OPTS="-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005" \